package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.formatter.Formatter;
import com.conversationboard.model.User;
import com.conversationboard.model.adminlog.AdminLog;
import com.conversationboard.model.adminlog.AdminLogEntry;

@WebServlet(name = "AdminUpdateAdminLogControllerServlet", urlPatterns = "/Admin/AdminUpdateAdminLogControllerServlet")
public class AdminUpdateAdminLogControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 3670694307143657744L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");

			int id = Integer.parseInt(request.getParameter("id"));
			String reason = (String) request.getParameter("reason");

			User user = User.get(request.getUserPrincipal().getName());

			if (!SecurityChecks.passes(request, user, this)) {
				return;
			}

			reason = Formatter.removeUnnecessaryWhitespace(reason);
			reason = Formatter.escapeHtml(reason);

			AdminLogEntry entry = AdminLog.getInstance().getItem(id);

			/*
			 * If you're the guy who entered this and (belt and braces) are an
			 * admin on this board
			 */

			if ((entry.getLoginId().equalsIgnoreCase(user.getLoginId())) && (user.isBoardAdmin(entry.getBoardId()))) {
				AdminLog.getInstance().editReason(user, id, reason);
			}

			RequestDispatcher dispatcher = request.getRequestDispatcher("/ViewAdminLogControllerServlet?pageNumber=0");
			dispatcher.forward(request, response);

		} catch (NumberFormatException e) {
		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
